package com.swust.book_shop.util;

/**
 * @author liushuai
 * @create 2022-05-09 22:52
 */



import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.Date;

    /**
     * Mianyang Qingmu Software Technology Co., Ltd.
     * Copyright (C) 2014-2019 All Rights Reserved.
     * Author: 1600107532@qq.com
     * Date: 2019/9/19 14:41
     * Description:
     */
    public class OSSUtil {
        private static String endpoint = "oss-cn-chengdu.aliyuncs.com";
        private static String accessKeyId = "LTAI5t7ezAMYmPASt9w27apY";
        private static String accessKeySecret = "sNThsK2BIFSk2fSVEAQvpslvaUv8mb";
        private static String bucketName = "swust-book-shop";

        /**
         * 文件默认存储时长
         */
        public final static long DEFAULT_EXPIRE_TIME = 10 * 365 * 24 * 3600;

        public static void main(String[] args) {
            // http://danger.oss-cn-shanghai.aliyuncs.com/30/36.pdf
            // String url = getUrl("1", "1.jpg", 86400);
            // System.out.println(url.toString());
            // createFolder(1);

        }

        public static String getEndpoint() {
            return endpoint;
        }

        public static void setEndpoint(String endpoint) {
            OSSUtil.endpoint = endpoint;
        }

        public static String getAccessKeyId() {
            return accessKeyId;
        }

        public static void setAccessKeyId(String accessKeyId) {
            OSSUtil.accessKeyId = accessKeyId;
        }

        public static String getAccessKeySecret() {
            return accessKeySecret;
        }

        public static void setAccessKeySecret(String accessKeySecret) {
            OSSUtil.accessKeySecret = accessKeySecret;
        }

        public static String getBucketName() {
            return bucketName;
        }

        public static void setBucketName(String bucketName) {
            OSSUtil.bucketName = bucketName;
        }

        public static long getDefaultExpireTime() {
            return DEFAULT_EXPIRE_TIME;
        }

        public static String getUrl(String fileKey) {
            return getUrl(fileKey, DEFAULT_EXPIRE_TIME);
        }

        /**
         * @param fileKey
         * @param expireTime 路径有效时间（秒）
         * @return
         */
        public static String getUrl(String fileKey, long expireTime) {
            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {
                Date expiration = new Date(System.currentTimeMillis() + 1000L * expireTime);

                URL url = client.generatePresignedUrl(bucketName, fileKey, expiration);
                client.shutdown();
                return url.toString();
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message: " + oe.getErrorCode());
                System.out.println("Error Code:       " + oe.getErrorCode());
                System.out.println("Request ID:      " + oe.getRequestId());
                System.out.println("Host ID:           " + oe.getHostId());
                client.shutdown();
                return null;
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
                client.shutdown();
                return null;
            }
        }

        /**
         * 获取预处理后的url，尤其适合图像
         *
         * @param fileKey
         * @param expireTime
         * @param process    详见阿里云OSS文档，如缩放图像：image/resize,m_fixed,w_100,h_100
         * @return
         */
        public static String getUrlByProcess(String fileKey, long expireTime, String process) {
            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {
                Date expiration = new Date(System.currentTimeMillis() + 1000L * expireTime);

                GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, fileKey, HttpMethod.GET);
                req.setExpiration(expiration);
                req.setProcess(process);

                URL url = client.generatePresignedUrl(req);
                client.shutdown();
                return url.toString();
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message: " + oe.getErrorCode());
                System.out.println("Error Code:       " + oe.getErrorCode());
                System.out.println("Request ID:      " + oe.getRequestId());
                System.out.println("Host ID:           " + oe.getHostId());
                client.shutdown();
                return null;
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
                client.shutdown();
                return null;
            }
        }

        /**
         * 上传文件
         *
         * @param multipartfile 文件数据流
         * @param fileKey       文件保存key，key可以含有‘/’，视为创建路径
         * @throws Throwable
         */
        public static String uploadFile(byte[] multipartfile, String fileKey) throws Throwable {
            if (multipartfile == null) {
                return null;
            }

            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {
                client.putObject(bucketName, fileKey, new ByteArrayInputStream(multipartfile));
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
            } finally {
                client.shutdown();
            }

            return getUrl(fileKey, DEFAULT_EXPIRE_TIME);
        }

        public static String uploadFile(String fileKey, String localFilePath) throws Throwable {
            if (StringUtils.isEmpty(localFilePath) || StringUtils.isEmpty(fileKey)) {
                    return null;
            }

            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {
                client.putObject(bucketName, fileKey, new File(localFilePath));
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());
            } finally {
                client.shutdown();
            }

            return getUrl(fileKey, DEFAULT_EXPIRE_TIME);
        }

        /**
         * 创建类别，为避免类别名冲突，key＝类别id
         *
         * @param categoryId
         */
        public static void createFolder(int categoryId) {
            String key = categoryId + "/";

            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            try {

                client.putObject(bucketName, key, new ByteArrayInputStream(new byte[0]));

            } catch (ClientException ce) {

                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ce.getMessage());

            } finally {

                client.shutdown();

            }
        }

    }

